import React from 'react';
import {bindActionCreators} from 'redux';
import Validator from 'async-validator';
import {connect} from 'react-redux';
import {ScrollView, Text, View} from 'react-native';
import Button from '../../components/button';
import Styles from '../../styles';
import * as ActionCreator from '../../actions/auth-actions';
import {FormStatus} from '../../reducers/app-state';
import _ from 'lodash';
import InputItem from '../../components/input-item';
import {getRealSize} from '../../utils';
import Toast from '../../components/toast';
import {I18n} from '../../reducers/intl';
import {NavigationActions, StackActions} from 'react-navigation';

class SignInScreen extends React.PureComponent {
  static navigationOptions = () => ({
    title: I18n.t('page.title.signIn'),
  });

  constructor() {
    super();
    this.state = {
      allowSubmit: true,
      errors: [],
    };
    this.validator = new Validator({
      username: [
        {
          required: true,
          message: I18n.t('form.validate.message.name'),
        },
        {
          min: 6,
          message: I18n.t('form.validate.message.minLength'),
        },
        {
          type: 'email',
          required: true,
          message: I18n.t('form.validate.message.email'),
        },
      ],
      password: [
        {
          required: true,
          message: I18n.t('form.validate.message.password'),
        },
        {
          min: 4,
          max: 18,
          message: I18n.t('form.validate.message.pwdRule'),
        },
      ],
    });
  }

  signIn = async () => {
    const {signInActions, navigation, signForm} = this.props;
    this.setState({allowSubmit: false});
    try {
      await signInActions.login(signForm);
      const resetAction = StackActions.reset({
        index: 0,
        actions: [NavigationActions.navigate({routeName: 'Main'})],
      });
      navigation.dispatch(resetAction);
    } catch (e) {
      console.log(e.message);
    }
    this.setState({allowSubmit: true});
  };

  onChangeValue = async (value, field) => {
    const {signForm, signInActions} = this.props;
    signInActions.update({[field]: value});
    const dataForm = {
      ...signForm,
      [field]: value,
    };
    try {
      await this.validator.validate(dataForm);
      this.setState({
        allowSubmit: true,
        errors: [],
      });
    } catch (e) {
      this.setState({
        allowSubmit: false,
        errors: e.errors,
      });
    }
  };

  onValidate = async () => {
    const {signForm} = this.props;
    try {
      await this.validator.validate(signForm);
      await this.signIn(signForm);
    } catch (e) {
      Toast.show(e.errors[0].message);
    }
  };

  render() {
    const {allowSubmit} = this.state;
    const {device, appState, signForm, navigation} = this.props;
    return (
      <ScrollView
        style={Styles.pageContainer}
        showsHorizontalScrollIndicator={false}
        showsVerticalScrollIndicator={false}>
        <View style={Styles.Layout.hidden}>
          <Text style={Styles.Front.version}>app: v{device.appVersion}</Text>
          <Text style={Styles.Front.version}>js: v{device.jsVersion}</Text>
        </View>
        <View style={[Styles.Layout.base.mt, Styles.Layout.base.mh]}>
          <InputItem
            placeholder={I18n.t('form.placeholder.email')}
            value={signForm.username}
            maxLength={18}
            onChange={value => this.onChangeValue(value, 'username')}
          />
        </View>
        <View style={[Styles.Layout.base.mt, Styles.Layout.base.mh]}>
          <InputItem
            placeholder={I18n.t('form.placeholder.password')}
            value={signForm.password}
            maxLength={18}
            password
            onChange={value => this.onChangeValue(value, 'password')}
          />
        </View>
        <View
          style={[
            Styles.Layout.flex.row,
            Styles.Layout.flex.between,
            Styles.Layout.base.mt,
            Styles.Layout.base.mh,
          ]}>
          <View style={[Styles.Layout.flex.row]}>
            <Text style={[Styles.Front.content.smallMed]}>
              {I18n.t('page.label.noAccount')}
            </Text>
            <Text
              style={[Styles.Front.content.smallMed, Styles.Color.link]}
              onPress={() => navigation.navigate('SelectRole')}>
              {I18n.t('page.label.register')}
            </Text>
          </View>
          <Text
            style={[Styles.Front.content.smallMed, Styles.Color.link]}
            onPress={() => navigation.navigate('ForgetPWD')}>
            {I18n.t('page.title.forget')}
          </Text>
        </View>
        <View style={[Styles.Layout.base.margin, {marginTop: getRealSize(40)}]}>
          <Button
            label={I18n.t('button.signIn')}
            disabled={!allowSubmit}
            onPress={_.debounce(this.onValidate, 500)}
            loading={appState.formStatus === FormStatus.PENDING}
          />
        </View>
      </ScrollView>
    );
  }
}

const mapStateToProps = state => ({
  appState: state.appState,
  device: state.device,
  user: state.user,
  token: state.token,
  signForm: state.signForm,
});

const mapDispatchToProps = dispatch => ({
  signInActions: bindActionCreators(ActionCreator, dispatch),
});

export default connect(mapStateToProps, mapDispatchToProps)(SignInScreen);
